package com.tomehay.termprojectmanage_server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tomehay.termprojectmanage_server.enums.ResponseCode;
import com.tomehay.termprojectmanage_server.mapper.StudentMapper;
import com.tomehay.termprojectmanage_server.pojo.Model.Clazz;
import com.tomehay.termprojectmanage_server.mapper.ClazzMapper;
import com.tomehay.termprojectmanage_server.pojo.Model.Student;
import com.tomehay.termprojectmanage_server.pojo.VO.ResultVO;
import com.tomehay.termprojectmanage_server.service.ClazzService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tomehay.termprojectmanage_server.utils.ShareCodeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomehay
 * @since 2023-06-20
 */
@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Resource
    ClazzMapper clazzMapper;

    @Resource
    StudentMapper studentMapper;


    @Override
    public ResultVO<List<Clazz>> GetAllClazz() {
        List<Clazz> clazzList = new ArrayList<>();
        clazzList = clazzMapper.selectList(null);
//        clazzMapper.
        return new ResultVO<>(ResponseCode.auto(clazzList),clazzList);
    }

    @Override
    public ResultVO<Void> removeClazz(int id) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);

        int flag = clazzMapper.delete(queryWrapper);

        if (flag == -1) {
            return new ResultVO<>(ResponseCode.FAILED);
        }

        queryWrapper.clear();
        queryWrapper.eq("clazz_id",id);
        flag = studentMapper.delete(queryWrapper);

        if (flag == -1) {
            return new ResultVO<>(ResponseCode.FAILED);
        }

        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> CreateClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());

        int flag = clazzMapper.insert(clazz);
        clazz.setInvitationCode(ShareCodeUtil.toSerialCode(clazz.getId()));
        clazz.setClazzCount(studentMapper.GetCounts(clazz.getId()));

        clazzMapper.updateById(clazz);

        if (flag == -1) {
            return new ResultVO<>(ResponseCode.FAILED);
        }

        return new ResultVO<>(ResponseCode.OK);
    }


}
